/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/9/26 20:32
 */
package com.gitee.mechanic.mybatis.handler;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.gitee.mechanic.core.constants.Status;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * 自定义填充公共字段
 *
 * @author mechanic
 */
public class AutoFillMetaObjectHandler extends MetaObjectHandler {
    /**
     * <p>
     * 插入元对象字段填充
     * </p>
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        setFieldValByName("status", Status.ACTIVE, metaObject);

        Object createTime = getFieldValByName("createTime", metaObject);
        if (createTime == null) {
            setFieldValByName("createTime", now, metaObject);
        }
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if (updateTime == null) {
            setFieldValByName("updateTime", now, metaObject);
        }
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if (updateTime == null) {
            setFieldValByName("updateTime", now, metaObject);
        }
    }
}
